<template>
  <div class="image-uploader">
    <div class="upload-area" @click="triggerFileInput" @drop.prevent="handleDrop" @dragover.prevent>
      <input 
        type="file" 
        ref="fileInput" 
        multiple 
        accept="image/*" 
        @change="handleFileChange" 
        style="display: none"
      >
      <div v-if="!images.length" class="upload-placeholder">
        <div class="upload-icon">
          <i class="fas fa-cloud-upload-alt"></i>
        </div>
        <p>点击或拖拽图片到此处上传</p>
        <p class="upload-hint">支持多个图片上传</p>
      </div>
    </div>

    <div class="category-info" v-if="images.length">
      <span class="image-count">已上传 {{ images.length }} 张图片</span>
      <button 
        v-if="images.length > previewLimit && !showAllImages" 
        @click="showAllImages = true" 
        class="show-all-btn"
      >
        显示全部
      </button>
      <button 
        v-if="showAllImages" 
        @click="showAllImages = false" 
        class="show-less-btn"
      >
        收起
      </button>
    </div>
    
    <div v-if="images.length" class="image-preview-list">
      <div 
        v-for="(image, index) in displayedImages" 
        :key="index" 
        class="image-preview-item"
      >
        <img :src="image.url" :alt="image.name">
        <div class="image-actions">
          <button class="delete-btn" @click="removeImage(index)">×</button>
        </div>
        <div class="image-info">
          <span class="image-name">{{ image.name }}</span>
          <span class="image-size">{{ formatSize(image.size) }}</span>
        </div>
      </div>
    </div>

    <div v-if="isProcessing" class="processing-overlay">
      <div class="processing-content">
        <div class="spinner"></div>
        <p>正在处理图片 ({{ processedCount }}/{{ totalFiles }})</p>
        <p class="processing-detail">{{ currentProcessingFile }}</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ImageUploader',
  props: {
    category: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      images: [],
      isProcessing: false,
      processedCount: 0,
      totalFiles: 0,
      currentProcessingFile: '',
      showAllImages: false,
      previewLimit: 4
    }
  },
  computed: {
    displayedImages() {
      return this.showAllImages ? this.images : this.images.slice(0, this.previewLimit)
    }
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    handleFileChange(event) {
      this.processFiles(event.target.files)
    },
    handleDrop(event) {
      this.processFiles(event.dataTransfer.files)
    },
    async processFiles(files) {
      try {
        this.isProcessing = true;
        this.processedCount = 0;
        this.totalFiles = files.length;
        
        for (const file of Array.from(files)) {
          if (file.type.startsWith('image/')) {
            this.currentProcessingFile = `处理中: ${file.name}`;
            
            try {
              const imageData = await this.processImage(file);
              this.images.push({
                file,
                url: imageData,
                name: file.name,
                size: file.size,
                label: this.category
              });
              this.processedCount++;
              this.$emit('upload', this.images);
            } catch (error) {
              console.error(`处理图片失败: ${file.name}`, error);
              // 显示错误提示
              this.$emit('error', `处理图片失败: ${file.name}`);
            }
          }
        }
      } catch (error) {
        console.error('处理图片时出错:', error);
        this.$emit('error', '处理图片时出错');
      } finally {
        this.isProcessing = false;
        this.currentProcessingFile = '';
      }
    },
    processImage(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => resolve(e.target.result);
        reader.onerror = () => reject(new Error(`读取文件失败: ${file.name}`));
        reader.readAsDataURL(file);
      });
    },
    removeImage(index) {
      this.images.splice(index, 1)
      this.$emit('upload', this.images)
    },
    formatSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
  },
  watch: {
    category: {
      handler(newCategory) {
        // Update all image labels when category changes
        this.images = this.images.map(image => ({
          ...image,
          label: newCategory
        }))
        this.$emit('upload', this.images)
      }
    }
  }
}
</script>

<style scoped>
.image-uploader {
  width: 100%;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
  background: white;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-placeholder {
  color: #909399;
}

.upload-icon {
  font-size: 28px;
  color: #909399;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  margin-top: 8px;
  color: #909399;
}

.image-preview-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  margin-top: 16px;
}

.image-preview-item {
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.image-preview-item img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  display: block;
}

.image-actions {
  position: absolute;
  top: 4px;
  right: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.image-preview-item:hover .image-actions {
  opacity: 1;
}

.delete-btn {
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  padding: 0;
  line-height: 1;
}

.delete-btn:hover {
  background: rgba(0, 0, 0, 0.7);
}

.image-info {
  padding: 8px;
  background: #f5f7fa;
}

.image-name {
  display: block;
  font-size: 12px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-size {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.processing-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.processing-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 15px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.processing-detail {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.category-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 10px 0;
}

.image-count {
  font-size: 14px;
  color: #606266;
}

.show-all-btn,
.show-less-btn {
  padding: 4px 12px;
  font-size: 12px;
  color: #409eff;
  background: none;
  border: 1px solid #409eff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.show-all-btn:hover,
.show-less-btn:hover {
  background: #ecf5ff;
}
</style> 